<?php

namespace App\Http\Controllers\Counter;

use App\Cost\CostInterface;
use App\Enums\PayChannel;
use App\Enums\TableStatus;
use App\Enums\TradeStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\TableTypeRequest;
use App\Http\Requests\Counter\TableTypeEditRequest;
use App\Http\Requests\Counter\TableRequest;
use App\Http\Requests\Counter\TableRepairRequest;
use App\Http\Requests\Counter\TableCheckRequest;
use App\Http\Resources\Counter\TableListResource;
use App\Http\Resources\Counter\TableTypeResource;
use App\Http\Resources\Counter\TableResource;
use App\Models\CostRule;
use App\Models\Member;
use App\Models\Order;
use App\Models\Store;
use App\Models\Table;
use App\Models\TableType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class TableController extends Controller
{
    public function getTableInfo(Table $table)
    {
        $table->load([
            'tableOrder.items.assistantUser',
            'tableOrder.items.costRule',
            'tableOrder.items.goods',
            'tableOrder.items.table.tableType',
        ]);

        return new TableListResource($table);
    }

    public function getTableTypes(\App\Enums\TableType $type)
    {
        $store = Auth::user()->store;

        $tableTypes = $store->tableTypes()
            ->withType($type)
            ->with([
                'tables.tableOrder.items.assistantUser',
                'tables.tableOrder.items.costRule',
                'costRules',
                'defaultRule'
            ])
            ->get();

        return TableTypeResource::collection($tableTypes);
    }

    public function getAllTableTypes()
    {
        $store = Auth::user()->store;

        $tableTypes = $store->tableTypes()
            ->with([
                'tables.tableOrder.items.assistantUser',
                'tables.tableOrder.items.costRule',
                'costRules',
                'defaultRule'
            ])
            ->get();

        return TableTypeResource::collection($tableTypes);
    }

    public function getStatusCounts()
    {
        /**
         * @var Store $store
         */
        $store = Auth::user()->store;
        //空闲
        $idleCount = Table::where('status', TableStatus::Idle)->whereHas('tableType', function ($query) use ($store) {
            $query->where('store_id', $store->id);
        })->count();

        //计时中
        $usedCount = Table::whereIn('status', TableStatus::getOpenedStatus())->whereHas('tableType', function ($query) use ($store) {
            $query->where('store_id', $store->id);
        })->count();

        //已停止
        $stopCount = 0;

        //已开灯
        $lightCount = 0;

        return ApiResponseHelper::json([
            'idle' => $idleCount,
            'used' => $usedCount,
            'stop' => $stopCount,
            'light' => $lightCount
        ]);
    }

    public function createType(TableTypeRequest $request)
    {
        DB::transaction(function () use ($request, &$tableType) {

            $tableType = TableType::create(array_merge($request->only([
                'name', 'start_num', 'default_people_count', 'type', 'count', 'default_rule_id'
            ]), ['store_id' => Auth::user()->store_id]));

            //rule
            $costRules = CostRule::whereIn('id', $request->input('cost_rule_ids'))->pluck('id')->toArray();
            $tableType->costRules()->attach($costRules);

            if ($tableType->type == \App\Enums\TableType::Room->value) {

                $tables = $request->input('tables');

                foreach ($tables as $table) {

                    $tableType->tables()->create([
                        'sort' => 0,
                        'name' => $table['name'],
                        'people_count' => $table['people_count'],
                        'type_id' => $tableType->id
                    ]);
                }
            } else {

                for ($i = 0; $i < $tableType->count; $i++) {

                    $tableType->tables()->create([
                        'sort' => $tableType->start_num + $i,
                        'name' => null,
                        'people_count' => $tableType->default_people_count,
                        'type_id' => $tableType->id
                    ]);
                }
            }
        });

        return new TableTypeResource($tableType);
    }

    public function editType(TableType $tableType, TableTypeEditRequest $request)
    {
        DB::transaction(function () use (&$tableType, $request) {

            $tableType->update($request->only([
                'name',
                'default_rule_id'
            ]));

            //rule
            $costRules = CostRule::whereIn('id', $request->input('cost_rule_ids'))->pluck('id')->toArray();
            $tableType->costRules()->detach();
            $tableType->costRules()->attach($costRules);
        });

        return new TableTypeResource($tableType);
    }

    public function deleteType(TableType $tableType)
    {
        if ($tableType->tables()->where('status', TableStatus::Used->value)->count() > 0)
            return ApiResponseHelper::json([], 400, '当前分类下，又已开启的球桌，无法删除!');

        DB::transaction(function () use ($tableType) {

            $tableType->tables()->delete();
            $tableType->delete();
        });

        return ApiResponseHelper::json([]);
    }

    public function addTable(TableType $tableType, TableRequest $request)
    {
        $table = $tableType->tables()->create($request->only([
            'sort', 'name',
        ]) + ['people_count' => $request->people_count ?? 0]);

        return new TableResource($table);
    }

    public function editTable(Table $table, TableRequest $request)
    {
        $table->update($request->only([
            'sort', 'name',
        ]) + ['people_count' => $request->people_count ?? 0]);

        return new TableResource($table);
    }

    public function deleteTable(Table $table)
    {
        if ($table->status == TableStatus::Used)
            return ApiResponseHelper::json([], 400, '球桌正在使用，无法删除!');

        $table->delete();

        return ApiResponseHelper::json([]);
    }

    public function repair(Table $table, TableRepairRequest $request)
    {
        $currentStatus = $table->status;
        if ($currentStatus == TableStatus::Repair)
            return ApiResponseHelper::json([], 400, '球桌正在维护中');

        if ($currentStatus == TableStatus::Used)
            return ApiResponseHelper::json([], 400, '球桌正在使用中');

        DB::transaction(function () use ($table, $request) {

            $table->repairLogs()->create(array_merge([
                'user_id' => Auth::id()
            ], $request->only(['comment'])));

            $table->status = TableStatus::Repair;
            $table->save();
        });

        return ApiResponseHelper::json([]);
    }

    public function unrepair(Table $table)
    {
        if ($table->status == TableStatus::Repair) {

            $table->status = TableStatus::Idle;
            $table->save();
        }

        return ApiResponseHelper::json([]);
    }
}
